import {useState} from 'react';
import {AuthApi} from "../../../api/auth.ts";
import {getUserInfo} from "../../../api/user.ts";
import {useAuthStore} from '../../../store/authStore'; // 引入 Zustand store

/**
 * 核心登录逻辑，现在直接使用 Zustand store。
 * @param data - 表单数据 (e.g., {username, password} or {phone, code})
 * @param loginMethod - 'password' or 'sms'
 */
export const executeLogin = async (
    data: any,
    loginMethod: 'password' | 'sms',
) => {
    let loginRes;

    // 根据登录方式调用不同的 API
    if (loginMethod === "password") {
        loginRes = await AuthApi.login({username: data.username, password: data.password});
    } else {
        loginRes = await AuthApi.smsLogin({mobile: data.phone, code: data.code});
    }

    if (loginRes.code !== 0 || !loginRes.data.accessToken) {
        throw new Error(loginRes.msg || '登录失败');
    }

    const {userId, expiresTime, accessToken, refreshToken} = loginRes.data;

    // 直接从 store 获取更新函数
    const {setAccessToken, setRefreshToken, setUserInfo} = useAuthStore.getState();

    // 更新 Token
    setAccessToken(accessToken);

    // 获取用户信息
    let userInfoRes;
    try {
        userInfoRes = await getUserInfo();
    } catch (error) {
        console.error('获取用户信息失败:', error);
        throw new Error('无法获取用户信息，请稍后重试。');
    }

    const newUserInfo = {
        userid: userId.toString(),
        password: data.password,
        username: data.username || '', // 短信登录时，username 可能为空
        token: accessToken, // 这个字段可以考虑移除，因为 accessToken 已经单独存储
        refreshToken, // 这个字段也可以考虑移除
        expiresTime,
        localStorageTime: Date.now(),
        nickname: userInfoRes?.data?.nickname || '',
        deptNamesStr: userInfoRes?.data?.deptNamesStr || '',
    };

    setUserInfo(newUserInfo);
    setRefreshToken(refreshToken);

    console.log('Token stored successfully!');
};


/**
 * 连接 UI 和业务逻辑的 React Hook。
 * @param navigation - 用于页面跳转
 */
export const useAuth = (navigation: any) => {
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const login = async (data: any, loginMethod: 'password' | 'sms') => {
        setIsLoading(true);
        setError(null);
        try {
            await executeLogin(data, loginMethod);
            navigation.reset({
                index: 0,
                routes: [{ name: 'Main' }],
            });
        } catch (e: any) {
            setError(e.message || "登录失败，请重试");
        } finally {
            setIsLoading(false);
        }
    };

    return {login, isLoading, error};
};